package cn.sky.demo.sso;

import cn.sky.demo.test.SessionRegistry;
import cn.sky.demo.test.UserInfo;
import cn.sky.demo.service.UserService;
import cn.sky.demo.test.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/sso")
public class SsoServerController {

    @Autowired
    private UserService userService;
    @Autowired
    private SessionRegistry sessionRegistry;
    
    @PostMapping("/login")
    public ResponseEntity<String> login(
            @RequestParam String username,
            @RequestParam String password,
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(required = false) String redirect) {
        
        // 验证用户凭证
        User user= userService.authenticate(username, password);
        if (user == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid credentials");
        }
        
        // 创建session并存储用户信息
        HttpSession session= request.getSession(true);
        session.setAttribute("USER_INFO", user);
        session.setMaxInactiveInterval(3600); // Session有效期1小时

        // 获取SessionID
        String sessionId= session.getId();
        sessionRegistry.registerSession(sessionId, session);
        // 设置Cookie
        Cookie cookie=new Cookie("SSO_SESSION_ID", sessionId);
        cookie.setMaxAge(3600); // 1小时有效期
        cookie.setPath("/");
        cookie.setDomain(".example.com"); // 关键：顶级域名，使所有子域都能访问
        cookie.setHttpOnly(true);
        cookie.setSecure(true); // 仅通过HTTPS传输
        
        response.addCookie(cookie);
        
        // 如果有重定向URL，则重定向回原应用
        if (redirect != null && !redirect.isEmpty()) {
            return ResponseEntity.status(HttpStatus.FOUND)
                .header("Location", redirect)
                .build();
        }
        
        return ResponseEntity.ok("Login successful");
    }
    
    @GetMapping("/validate")
    public ResponseEntity<UserInfo> validateSession(
            @CookieValue(name = "SSO_SESSION_ID", required = false) String sessionId) {
        
        if (sessionId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        // 验证Session有效性并获取用户信息
        HttpSession session= sessionRegistry.getSession(sessionId);
        if (session == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        // 从Session获取用户信息
        User user= (User) session.getAttribute("USER_INFO");
        if (user == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        // 返回用户信息
        UserInfo userInfo=new UserInfo(user.getId(), user.getUsername(), user.getRoles());
        return ResponseEntity.ok(userInfo);
    }
    
    @PostMapping("/logout")
    public ResponseEntity<Void> logout(
            @CookieValue(name = "SSO_SESSION_ID", required = false) String sessionId,
            HttpServletResponse response,
            @RequestParam(required = false) String redirect) {
        
        // 使Session失效
        if (sessionId != null) {
            HttpSession session= sessionRegistry.getSession(sessionId);
            if (session != null) {
                session.invalidate();
            }
        }
        
        // 删除Cookie
        Cookie cookie=new Cookie("SSO_SESSION_ID", null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        cookie.setDomain(".example.com");
        response.addCookie(cookie);
        
        // 如果有重定向URL，则重定向
        if (redirect != null && !redirect.isEmpty()) {
            return ResponseEntity.status(HttpStatus.FOUND)
                .header("Location", redirect)
                .build();
        }
        
        return ResponseEntity.ok().build();
    }
}